package com.java.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author jl
 * Created on 2020/9/27
 */
public class NIOServer {

    public static void main(String[] args) throws Exception {
        // 创建ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 创建selector
        Selector selector = Selector.open();
        // serverSocketChannel绑定端口6666, 在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        // serverSocketChannel设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 将serverSocketChannel注册到selector,并监听OP_ACCEPT事件(接收客户端连接)
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("注册后的SelectionKey 数量=" + selector.keys().size());

        // 循环等待客户端连接
        while (true) {
            // 等待1秒，如果没有事件发生, selector.select()返回有事件发生的通道的个数
            if (selector.select() == 0) {
                System.out.println("服务器等待了1秒,无连接");
                continue;
            }
            // selector.selectedKeys() 返回关注事件SelectionKey的集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            System.out.println("selectionKeys 数量 = " + selectionKeys.size());
            //遍历 Set<SelectionKey>, 使用迭代器遍历
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                // 获取到SelectionKey
                SelectionKey key = keyIterator.next();
                // 根据key 对应的通道发生的事件做相应处理
                if (key.isAcceptable()) { // 如果是 OP_ACCEPT, 有新的客户端连接
                    // 给该客户端生成一个 SocketChannel, 这里的accept()不用阻塞,因为已经明确知道有accept事件发生了
                    // serverSocketChannel.accept()接收一个连接,返回代表这个连接的通道对象
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode());
                    // 将SocketChannel 设置为非阻塞
                    socketChannel.configureBlocking(false);
                    // 将socketChannel 注册到selector, 关注事件为 OP_READ， 同时给socketChannel关联一个Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("客户端连接后 ，注册的SelectionKey 数量=" + selector.keys().size());
                }

                if (key.isReadable()) { // 如果是 OP_READ
                    // 通过key反向获取到对应SocketChannel
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    // 从channel中读取数据到buffer
                    channel.read(buffer);
                    System.out.println("来自客户端的消息: " + new String(buffer.array()));
                }

                //手动从集合中移动当前的selectionKey, 防止重复操作
                keyIterator.remove();
            }
        }
    }
}
